package cn.gok.hotelback.controller;

import cn.gok.hotelback.entity.User;
import cn.gok.hotelback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/checklogin")
    public Map<String, Object> checkLogin(@RequestBody User user, HttpSession session) {
        User loginUser = userService.checkLogin(user.getUsername(), user.getPassword());
        Map<String, Object> result = new HashMap<>();
        if (loginUser != null) {
            session.setAttribute("userId", loginUser.getUserId());
            session.setAttribute("username", loginUser.getUsername());
            result.put("status", "success");
            result.put("userId", loginUser.getUserId());
            result.put("username", loginUser.getUsername());
        } else {
            result.put("status", "fail");
        }
        return result;
    }

    @PostMapping("/register")
    public String register(@RequestBody User user) {
        try {
            boolean result = userService.register(user);
            return result ? "success" : "fail";
        } catch (Exception e) {
            return "error";
        }
    }

    @GetMapping("/members")
    public java.util.List<User> listMembers(HttpSession session) {
        return userService.findAllMembers();
    }
    @PostMapping("/setLevel")
    public String setMemberLevel(@RequestParam Integer userId, @RequestParam Integer level) {
        if (level < 1 || level > 8) return "invalid_level";
        return userService.setUserLevel(userId, level) ? "success" : "fail";
    }
} 